package com.quan.sport.city.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.core.support.BaseController;
import com.quan.common.properties.WeixinConfigProperties;
import com.quan.common.utils.IpHelper;
import com.quan.sdk.weixin.constant.API;
import com.quan.sdk.weixin.model.OAuthAccessToken;
import com.quan.sdk.weixin.model.OAuthUser;
import com.quan.sdk.weixin.utils.WeixinUtil;
import com.quan.sport.city.entity.SportCityUser;
import com.quan.sport.city.service.SportCityUserService;

/**
 * <p>
 * 同城运动-会员登录
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-06-24
 */
@RestController
@RequestMapping("/sport")
public class WeixinController extends BaseController {

	@Autowired
	private WeixinConfigProperties weixinConfigProperties;
	
	@Autowired 
    private SportCityUserService service;
	
	// APP（我的）界面
	private static final String MY_URL = "http://yhaoquan-wx.wicp.net/#/user/index";
	
	// APP手机号绑定页面，参数openid
	private static final String BANDING_URL = "http://yhaoquan-wx.wicp.net/#/banding?openid=%s";

	// 微信授权回调地址
	private static final String REDIRECT_URL = "http://yhaoquan.imwork.net/sport/weixin/callback";

	@GetMapping(value = "/weixin/login")
	public void weixinLogin() {
		
		// 第一步：用户同意授权，获取code
		String getCodeUrl = API.get(API.OAUTH_CODE_URL, this.weixinConfigProperties.getAppId(), REDIRECT_URL, "snsapi_userinfo", "STATE");

		System.out.println(getCodeUrl);
		try {
			this.response.sendRedirect(getCodeUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@GetMapping(value = "/weixin/callback")
	public void weixinCallBack() {
		this.logger.info("微信授权回调>>>>");

		try {
			// 接收微信传回的code参数
			String code = request.getParameter("code");
	
			// 第二步：通过code换取网页授权access_token
			String getAccessTokenUrl = API.get(API.OAUTH_CODE_ACCESS_TOKEN_URL,this.weixinConfigProperties.getAppId(), this.weixinConfigProperties.getAppSecret(), code);
			OAuthAccessToken accessToken = WeixinUtil.doGet(getAccessTokenUrl).asBean(OAuthAccessToken.class);
			
			if(null != accessToken) {
				String getUserInfoUrl = API.get(API.OAUTH_GET_USER_INFO_URL, accessToken.getAccess_token(), accessToken.getOpenid());
				OAuthUser oAuthUser = WeixinUtil.doGet(getUserInfoUrl).asBean(OAuthUser.class) ;
				
				//根据OPENID查找用户
				SportCityUser user = this.service.findByOpenId(oAuthUser.getOpenid()) ;
				if(null != user) { //用户存在
					
					if(StringUtils.isBlank(user.getMobile())) {//用户未绑定手机号，跳转到绑定手机号页面
						logger.info("用户未绑定手机号，跳转到绑定手机号页面");
						this.response.sendRedirect(String.format(BANDING_URL, oAuthUser.getOpenid()));
					} else {
						//用户存在并绑定了手机号，跳转到业务页面
						logger.info("用户存在并绑定了手机号，跳转到业务页面");
						this.response.sendRedirect(MY_URL);
					}
					
					
				} else { //用户不存在
					//保存用户信息
					SportCityUser entity = new SportCityUser() ;
					entity.setCity(oAuthUser.getCity());
					entity.setCountry(oAuthUser.getCountry());
					entity.setHeadimgurl(oAuthUser.getHeadimgurl());
					entity.setNickname(oAuthUser.getNickname());
					entity.setProvince(oAuthUser.getProvince());
					entity.setSex(Integer.parseInt(oAuthUser.getSex()));
					entity.setOpenid(oAuthUser.getOpenid());
					this.service.insertSelective(entity) ;
					
					//跳转到绑定手机号页面
					this.response.sendRedirect(String.format(BANDING_URL, oAuthUser.getOpenid()));
				}
			}
			
			System.out.println(accessToken);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * JS-SDK Config 参数配置
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping(value="/weixin/jssdk/config")
	public Object config(HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> jssdkConfig = WeixinUtil.getJSSDKConfig(request) ;
			
			logger.info("访问IP：[{}]，JSSDK配置参数：{}", IpHelper.getIpAddr(request), JSON.toJSONString(jssdkConfig));
			
			return jssdkConfig;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultBean.failure();
	}

}
